<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <title>订单结算</title>
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=0">
    <link rel="stylesheet" href="/node_modules/LobsterUIFrame/weui/css/weui.css" />
    <link rel="stylesheet" href="/node_modules/LobsterUIFrame/weui/css/weuix.css" />
    <script src="/node_modules/LobsterUIFrame/weui/js/zepto.min.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/zepto.weui.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/swipe.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/macy.js"></script>
    <script src="/node_modules/LobsterUIFrame/weui/js/php.js"></script>
    <script src="/lobstersdk/lobster.js"></script>
    <script src="/jslib/template-web.js"></script>
    <style>
        .bottom {
            background-color: #F5F5F5;
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            align-items: center;
            display: flex;
            padding: 10px 4px;
        }

        .weui-btn {
            height: 40px;
            line-height: 40px;
        }

        .bottomimg {
            height: 30px;
            width: 30px;
        }
    </style>
</head>

<body ontouchstart>
    <div class="weui-cell weui-cell_access" id="address">
        <div class="weui-cell__bd">
            <span>请选择收货地址</span>
        </div>
        <div class="weui-cell__ft"></div>
    </div>
    <div style="height: 10px;background-color:#F5F5F5;"></div>
    <div class="weui-panel__hd">商品</div>
    <div class="weui-panel__bd" id="goods">

    </div>
    <div style="height:50px;">

    </div>
    <div class="bottom">
        <div style="flex:3;text-align: center;" id="price">
            共1件，实际支付：￥1.00
        </div>
        <div style="flex:2;text-align:right;">
            <a style="border-radius: 0;" href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary"
                id="generateOrder"></i>确认下单</a>
        </div>
    </div>
    <div id="half2" class='weui-popup__container popup-bottom'>
        <div class="weui-popup__overlay"></div>
        <div class="weui-popup__modal">
            <div class="toolbar">
                <div class="toolbar-inner">
                    <a href="javascript:;" class="picker-button close-popup">关闭</a>
                    <h1 class="title">选择地址</h1>
                </div>
            </div>
            <div class="modal-content">
                <div class="weui-panel__bd" id="addresslist">
                </div>
            </div>
        </div>
    </div>
</body>

</html>
<script type="text/template" id="goodstemp">
    {{each list item}}
    <a href="javascript:void(0);" class="weui-media-box weui-media-box_appmsg">
        <div class="weui-media-box__hd">
            <img class="weui-media-box__thumb" src="{{item.SpecImg}}" alt="">
        </div>
        <div class="weui-media-box__bd">
            <h4 class="weui-media-box__title">{{item.GoodsName}}</h4>
            <p class="weui-media-box__desc">规格 {{item.SpecName}}</p>
            <div class="weui-media-box__desc" style="display: flex;"> ￥{{item.GoodsPrice}} <div style="flex:1;text-align:right">
                </div>x{{item.GoodsNum}}</div>
        </div>
    </a>
    {{/each}}
</script>

<script type="text/template" id="addresslisttemp">
    {{each list item}} 
        <div class="weui-media-box weui-media-box_text addressitem" data-item="{{item}}">
            <h4 class="weui-media-box__title">{{item.Addressee}} | {{item.Tel}}
                {{if(item.IsDefault==1)}}
                        <label class="label f-white bg-green">默认</label>
                        {{/if}}
            </h4>
            <p class="weui-media-box__desc">{{item.AreaInfo}}</p>
        </div>
    {{/each}} 
    <!-- {{if(list.length<5)}}
    <div class="bottom">
        <a href="javascript:;" class="weui-btn weui-btn_primary" id="add">+新增收货地址</a> 
    </div>
    {{/if}} -->
</script>
<script>

    lobsterh5.main({
        data: {
            address: {},
            addressList: [],
            goods: [],
            total: 0,
            num: 0,
        },
        //初始化页面
        pageload: function () {
            this.data.address = JSON.parse(localStorage.getItem("address")) || {};
            if (this.data.address.AreaInfo) {
                var address = this.data.address;
                var addresshtml = "<div><div>" + address.Addressee + "|" + address.Tel + "</div><div>" + address.AreaInfo + "</div></div>";
                $("#address").html(addresshtml);
            }

            this.data.goods = JSON.parse(lobsterh5.GetUrlParam("goods", decodeURIComponent(location.href)));
            var html = template("goodstemp", { list: this.data.goods });
            this.data.total = this.sum(this.data.goods.map(n => (parseInt(n.GoodsNum) * parseFloat(n.GoodsPrice)))).toFixed(2);
            this.data.num = this.sum(this.data.goods.map(n => parseInt(n.GoodsNum)));
            $("#price").text("共" + this.data.num + "件，实际支付：￥" + this.data.total);
            $("#goods").html(html);
            this.getaddress();
            this.initevent();
        },
        debounce: function (fn, interval) {
            let timer = null; // 定时器
            return function () {
                // 清除上一次的定时器
                clearTimeout(timer);
                // 拿到当前的函数作用域
                let _this = this;
                // 拿到当前函数的参数数组
                let args = Array.prototype.slice.call(arguments, 0);
                // 开启倒计时定时器
                timer = setTimeout(function () {
                    // 通过apply传递当前函数this，以及参数
                    fn.apply(_this, args);
                    // 默认300ms执行
                }, interval || 300)
            }
        },
        //初始化事件
        initevent: function () {
            var self = this;
            $("#generateOrder").click(function () {
                if ((self.data.address.AddressID || 0) == 0) {
                    $.toast("请选择收货地址", 'text');
                    return;
                }
                if (self.data.total == 0) {
                    $.toast("金额不能为0", 'text');
                    return;
                }
                $.showLoading("提交订单中");
                lobsterh5.POST("/lowcode/APP20200616102057595/shop/?fun=mall.generateorder", {
                    order: JSON.stringify({
                        OrderNo: '',
                        TotalFee: self.data.total,
                        UserId: localStorage.getItem("userId")
                    }),
                    goods: JSON.stringify(self.data.goods),
                    address: JSON.stringify({
                        Name: self.data.address.Addressee,
                        TelePhone: self.data.address.Tel,
                        Province: self.data.address.Province,
                        City: self.data.address.City,
                        Area: self.data.address.District,
                        Address: self.data.address.Street
                    })
                }).then(neworderno => {
                    var price = self.data.total * 100;
                    lobsterh5.CALLOUTSERVICE("wallet.wallet.pretransaction", {
                        SubMchId: '20220505085609644323',
                        BusinessOrderNo: neworderno,
                        OrderType: 3,//业务类型 1预约挂号 2自助缴费
                        PayType: 1,//默认1 微信支付
                        PayScene:1,//1 h5 2小程序 3app
                        Price: price, //单位分
                        Body: '商品购买',//商品描述
                        Memo: self.data.goods.map(n => n.GoodsName).join(";"),//可以不填
                        tradelist: JSON.stringify([{ UserId:localStorage.getItem("userId"), Amount: price, TradeMethod: 0, FinancialBalance: 2 }
                            , { UserId: "6117", Amount: price, TradeMethod: 0, FinancialBalance: 1 }])
                    }).then(res => {
                        $.hideLoading();
                        location = res.payredirecturl;
                    }).catch(res => {
                        $.toast(res.msg, 'forbidden');
                    });
                }).catch(res => {
                    $.toast(res.msg, 'forbidden');
                })
            })
            $("#address").click(function () {
                $("#half2").popup();//打开 
            })
            $("#addresslist").on("click", '.addressitem', function () {
                $.closePopup();
                var address = $(this).data("item");
                localStorage.setItem("address", JSON.stringify(address));
                var addresshtml = "<div><div>" + address.Addressee + "|" + address.Tel + "</div><div>" + address.AreaInfo + "</div></div>";
                $("#address").html(addresshtml);
                self.data.address = address;
            });
        },
        getaddress: function () {
            var self = this;
            lobsterh5.GET("/sso/v1/patient/GetAddressList", {
                goodsId: self.data.goodsId
            }).then(res => {
                var addressList = res.addressList;
                if (addressList && addressList.length > 0) {
                    addressList.forEach((item, index) => {
                        item.AreaInfo = item.Province + item.City + item
                            .District + " " + item.Street; //地址信息
                    });
                    self.data.addressList = addressList;
                }
                self.initaddress();

            }).catch(res => {
                $.toast(res.msg, 'forbidden');
            })
        },
        initaddress: function () {
            var html = template("addresslisttemp", { list: this.data.addressList });
            $("#addresslist").html(html);
        },
        sum(arr) {
            var s = 0;
            for (var i = arr.length - 1; i >= 0; i--) {
                s += arr[i];
            }
            return s;
        },
    })
</script>